import Taro, {Component} from '@tarojs/taro'
import {View, Text, Image, Picker} from '@tarojs/components'

import {
  AtInput,
  AtTextarea,

} from 'taro-ui'

import './shopRegister.scss'

import DataManager from '../../utils/DataManager.js'
import {STORAGE_KEY} from "../../utils/const";

import addImage from '../../image/ic_add_image.png'
import baseUrl from '../../network/config'
import BasePage from "../basePage";

import locationIcon from '../../image/ic_location.png'


export default class shopRegister extends BasePage {
  config = {
    navigationBarTitleText: '成为商家'
  }

  constructor(props) {
    super(props)
    this.state = {
      businessName: '',
      businessMobile: '',
      intro: '',
      address: '',
      longitude: '',
      latitude: '',
      addressImage: '',
      localImage: addImage,
      categoryName: '',
      categoryId: '',
      categoryViewShow: false,
      categories: []
    }
  }

  onPullDownRefresh(){
    Taro.stopPullDownRefresh();
  }

  componentDidMount() {

    this.auth = DataManager.getAuthInfo();

    let data = { platform: 'android_c', loginChannel: 'c', type: 'business'};

    Object.assign(data,this.auth)

    Taro.request({
      url: 'https://www.vpin.top/a/stateless/dict/dictList',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'GET',
      dataType: 'json',
      data: data,
      success: (obj) => {

        const reps = obj.data.data;
        const categories = reps.map((d) => {
          return {name: d.name, code: d.code}
        });

        this.setState({categories: categories})

      },
      fail: (obj) => {
        Taro.showToast({
          title: '程序异常',
          icon: 'none',
          duration: 1000
        })

      }
    })


  }

  onShopNameChange(shopName) {
    this.setState({
      businessName: shopName,
    })
  }

  onShopMobileChange(shopMobile) {
    this.setState({
      businessMobile: shopMobile
    })
  }

  onShopDescChange(e) {
    this.setState({
      intro: e.target.value
    })
  }

  onShopAddressChange(address) {
    this.setState({
      address: address,
    })
  }

  onChooseLocation() {
    Taro.getSetting({
      success(res){
        if (!res.authSetting['scope.userLocation']) {
          Taro.authorize({
            scope: 'scope.userLocation',
            success() {

            },
          })
        }
      }
    })
     let _this = this;
     Taro.chooseLocation({
       success(res2) {
         _this.setState({
           address: res2.address,
           longitude: res2.longitude,
           latitude: res2.latitude
         })
       }
     })
  }

  uploadHeadImage(params) {

    let baseParams = { platform: 'android_c', loginChannel: 'c' };
    Object.assign(params, baseParams,this.auth)
    params.success = (res) => {
      const d =  JSON.parse(res.data)
      if (d.status == 'success') {
        this.setState({addressImage: d.data[0],localImage:params.filePath})
      }
    }

    params.fail = (obj) => {
      console.log(obj)
    }

    Taro.uploadFile(params);

  }

  onChosenImage() {
    let _this = this
    Taro.chooseImage({
      sizeType:['compressed'],
      sourceType: ['album', 'camera'],
      count: 1,
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        let tempFilePath = res.tempFilePaths[0]
        let params = {
          filePath: tempFilePath,
          name: 'imageName',
          url: 'https://www.vpin.top/a/stateless/image/fileUpload'
        }
        _this.uploadHeadImage(params)
      },
      fail(obj) {
        console.log(obj)
      }
    })
  }


  onChooseCategory(e) {
    const code = this.state.categories[e.detail.value].code;
    this.setState({categoryId: code})
    this.setState({categoryName: this.state.categories[e.detail.value].name})
  }

  commitParamsCheck(){
    let checked = false;
    let hint = '';
    if (!this.state.categoryName){
      hint = '请选择商家类型'
    } else if (!this.state.businessName){
      hint = '请填写商家名称'
    } else if (!this.state.businessMobile) {
      hint = '请填写联系电话'
    } else if (!this.state.address){
      hint = '请填写商家地址'
    } else if (!this.state.intro) {
      hint = '请填写商家简介'
    } else if (this.state.localImage == addImage){
      hint = '请选择商家头像'
    } else {
      checked = true;
    }
    if (!checked){
      Taro.showToast({
        title:hint,
        icon:'none'
      })
    }

    return checked;
  }

  onSubmit() {

    if (!this.commitParamsCheck()){
      return;
    }

    let data = {
      platform: 'android_c', loginChannel: 'c',
      businessName: this.state.businessName, address: this.state.address, addressImage: this.state.addressImage,
      intro: this.state.intro,
      longitude: this.state.longitude,
      latitude: this.state.latitude,
      categoryId: this.state.categoryId,
      businessMobile: this.state.businessMobile,
    };

    Object.assign(data,this.auth);


    Taro.request({
      url: 'https://www.vpin.top/a/rest/business/saveBusinessInfo',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      dataType: 'json',
      data: data,
      success: (obj) => {
        if (obj.data.status == 'success') {

          Taro.setStorageSync(STORAGE_KEY.IS_BUSINESS , 1);
          Taro.setStorageSync(STORAGE_KEY.BUSINESS_MOBILE , this.state.businessMobile);

          Taro.showToast({
            title: '注册成功',
            icon: 'success',
            duration: 1000
          });
          setTimeout(()=>{
            Taro.navigateBack({delta: 1});
          },1000)

        } else {

          Taro.showToast({
            title: '注册失败',
            icon: 'none',
            duration: 1000
          })
        }
      },
      fail: (obj) => {
        Taro.showToast({
          title: '程序异常',
          icon: 'none',
          duration: 1000
        })
      }
    })
  }

  render() {

    let catName = this.state.categoryName ? this.state.categoryName : '请选择商家类型';

    return (
      <View className='shop-register-container'>

        <Picker mode='selector' range={this.state.categories} rangeKey='name' value='0'
                onChange={this.onChooseCategory.bind(this)}>
          <View className='shop-register-picker'>
            <Text className='shop-register-type-text'>商家类型</Text>
            <Text className='shop-register-type-text'>{catName}</Text>
          </View>
        </Picker>

        <View className='shop-register-divider' style='margin-left:20px'></View>

        <View className='shop-register-container-sub'>
          <AtInput
            style='text-align: right;max-lines:1;height:45px'
            name='shopName'
            value={this.state.businessName}
            clear
            title='商家名称'
            type='text'
            placeholder='请填写商家名称'
            border
            maxlength={50}
            onChange={this.onShopNameChange.bind(this)}
          />
          <View className='shop-post-choose-add' onClick={this.onChosenImage.bind(this)}>
            <Text className='shop-post-add-hint'>商家头像</Text>
            <Image className='shop-register-image' src={this.state.localImage}></Image>

          </View>
          <View className='shop-register-divider'></View>
          <AtInput
            style='text-align: right;max-lines:1;height:45px'
            name='shopMobile'
            value={this.state.businessMobile}
            clear
            title='联系电话'
            type='number'
            placeholder='请填写联系电话'
            border
            maxlength={50}
            onChange={this.onShopMobileChange.bind(this)}
          />
          <AtInput
            style='text-align: right;max-lines:1;height:45px'
            name='shopAddress'
            value={this.state.address}
            title='商家地址'
            type='text'
            placeholder='请填写商家地址'
            border
            maxlength={50}
            onChange={this.onShopAddressChange.bind(this)}
          >
            <Image style='width: 20px;height: 20px;' src={locationIcon}  onClick={this.onChooseLocation.bind(this)}></Image>
          </AtInput>
          <View className='shop-register-divider'></View>
          <View className='shop-post-choose-add'>
            <Text className='shop-post-add-hint'>商家简介</Text>
          </View>
          <AtTextarea
            style='margin-right:20px'
            value={this.state.intro}
            maxlength='300'
            placeholder='请填写商家简介'
            onChange={this.onShopDescChange.bind(this)}
          />
        </View>
        <View className='shop-register-commit-container'>
          <Text className='shop-register-commit' onClick={this.onSubmit.bind(this)}>提交</Text>
        </View>
      </View>
    )
  }

}

